# -*- coding: utf-8 -*-
from api.models import *
from django.conf import settings
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.core.cache import cache
import json
import xml.dom.minidom
import urllib2

PARTS = {}
API_URL = 'http://ws.audioscrobbler.com/2.0/?'


def index(request):
    return render_to_response('index.html')


def load(request):
    hashes=SongsHash.objects.all()
    for hash in hashes:
        create_parts(hash.hash, hash.id)
    return HttpResponse('ok')

def add(request):
    #TODO: хеш для проверки запроса к апи.
    song = request.GET.get('song')
    title = request.GET.get('title')
    if not title:
        title = 'test'
    author = request.GET.get('author')
    length = request.GET.get('length')
    album = request.GET.get('album')
    if song and title:
        if author:
            data = urllib2.urlopen('%smethod=track.getinfo&track=%s&artist=%s&api_key=%s' % (API_URL, title, author, settings.LAST_FM_KEY)).read()
            print data
            xmlfile = xml.dom.minidom.parseString(data)
            info = xmlfile.getElementsByTagName('album')
            duration = xmlfile.getElementsByTagName('duration')
            if duration:
                duration = duration[0].childNodes[0].data
            if info:
                album = info[0].getElementsByTagName('title')
                if album:
                    album = album[0].childNodes[0].data
        obj, created = SongsHash.objects.get_or_create(hash=song)
        if created:
            SongData.objects.create(
                song=obj,
                title=title,
                author=author,
                album=album,
                length = duration
            )
            create_parts(song, obj.id)
    else:
        return HttpResponse('Error!!!')
    return HttpResponse('ok')

def search(request):
    song_part = request.GET.get('song')
    if song_part:
        chunks=[]
        for i in xrange(len(song_part)-settings.CHUNK_SIZE+1):
            chunk = song_part[i:i+settings.CHUNK_SIZE]
            chunks.append(chunk)
        result = {}
        for part in chunks:
            try:
                result[part]=PARTS[part]
            except:
                pass
        matrix={}
        for key in result:
            for id in result[key]:
                try:
                    matrix[int(id)]+=1
                except:
                    matrix[int(id)]=int(id)
        if matrix:
            matrix = sorted(matrix.items(), key=lambda x: -x[1])
            if matrix[0][1]<10:
                return HttpResponse(json.dumps({'song':'not_found'}))
        else:
            return HttpResponse(json.dumps({'song':'not_found'}))
        prev = 0
        answer = []
        for x in matrix:
            if x[1]<prev:
                break
            else:
                answer.append(x[0])
                prev = x[1]
        if len(answer)>1:
            songs = SongData.objects.filter(song__in = answer)
        else:
            songs = SongData.objects.filter(song = answer[0])
        print songs
        json_answer = []
        for song in songs:
            json_answer.append({
                'song':{
                    'title':song.title,
                    'artist':song.author
                }
            })
        return render_to_response('index.html', {'songs': songs})
        #return HttpResponse(json.dumps(json_answer))

def create_parts(song_hash, id, ):
    for i in xrange(len(song_hash)-settings.CHUNK_SIZE+1):
        chunk = song_hash[i:i+settings.CHUNK_SIZE]
        try:
            PARTS[chunk].append(id)
        except:
            PARTS[chunk]=[]
            PARTS[chunk].append(id)
